<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="./utils/reset.css" />
    <title>08绘制线段</title>
  </head>
  <body>
    <canvas id="canvas"></canvas>

    <script type="shader-source" id="vertexShader">
      precision mediump float;
      attribute vec2 triangle_Position;
      attribute vec2 canvas_Size;
      void main(){
        vec2 position = (triangle_Position / canvas_Size) * 2.0 - 1.0;
        position = position * vec2(1.0, -1.0);
        gl_Position = vec4(position, 0.0, 1.0);
        gl_PointSize = 10.0;
      }
    </script>
    <script type="shader-source" id="fragmentShader">
      void main(){
        gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
      }
    </script>

    <script src="./utils/webgl-helper.js"></script>

    <script>
      const canvas = getCanvas("#canvas");
      resizeCanvas(canvas);
      const gl = getContext(canvas);
      const vertexShader = createShaderFromScript(
        gl,
        gl.VERTEX_SHADER,
        "vertexShader"
      );

      const fragmentShader = createShaderFromScript(
        gl,
        gl.FRAGMENT_SHADER,
        "fragmentShader"
      );

      const program = createSimpleProgram(gl, vertexShader, fragmentShader);
      gl.useProgram(program);

      const triangle_Position = gl.getAttribLocation(
        program,
        "triangle_Position"
      );
      const canvas_Size = gl.getAttribLocation(program, "canvas_Size");

      const positions = [];
      gl.vertexAttrib2f(canvas_Size, canvas.width, canvas.height);

      // 创建缓冲区
      const vertexBuffer = gl.createBuffer();
      // 将webgl与缓冲区绑定
      gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
      // 设置顶点属性从缓冲区中读取数据的方式
      gl.vertexAttribPointer(triangle_Position, 2, gl.FLOAT, false, 0, 0);

      gl.enableVertexAttribArray(triangle_Position);

      canvas.addEventListener("click", ({ pageX, pageY }) => {
        positions.push(pageX, pageY);
        if (positions.length > 0) {
          // 向缓冲区中写入数据
          gl.bufferData(
            gl.ARRAY_BUFFER,
            new Float32Array(positions),
            gl.STATIC_DRAW
          );
          render(gl);
        }
      });

      function render(gl) {
        gl.clear(gl.COLOR_BUFFER_BIT);
        if (positions.length > 0) {
          // 根据两个点绘制直线
          //   gl.drawArrays(gl.LINES, 0, positions.length / 2);
          // 绘制连续线段
          gl.drawArrays(gl.LINE_STRIP, 0, positions.length / 2);
          // 绘制闭环线段
          //   gl.drawArrays(gl.LINE_LOOP, 0, positions.length / 2);
        }
      }

      gl.clearColor(0, 0, 0, 1);
      render(gl);
    </script>
  </body>
</html>
